<?php

App::uses('AppModel', 'Model');
App::uses('AuthComponent', 'Controller/Component');

/**
 * User Model
 *
 */
class User extends AppModel
{

    public $name = 'User';
    public $primaryKey = 'id';
    public $validate = array();
    public $belongsTo = array(
        'Usergroup' => array(
            'className' => 'Usergroup',
            'foreignKey' => 'groupId'
        )
    );
    public $actsAs = array('Acl' => array('type' => 'requester', 'enabled' => false));

    public function beforeSave($options = array())
    {
        $this->data['User']['password'] = AuthComponent::password($this->data['User']['password']);
        return true;
    }

    /**
     * automagic connection of user, group with the Acl tables
     * @return null
     */
    public function parentNode()
    {
        if (!$this->id && empty($this->data)) {
            return null;
        }
        if (isset($this->data['User']['groupId'])) {
            $groupId = $this->data['User']['groupId'];
        } else {
            $groupId = $this->field('groupId');
        }
        if (!$groupId) {
            return null;
        } else {
            return array('Usergroup' => array('id' => $groupId));
        }
    }

    /**
     * automagic connection of user, group with the Acl tables, only group
     * @return null
     */
    public function bindNode($user)
    {
        return array('model' => 'Usergroup', 'foreign_key' => $user['User']['groupId']);
    }

}
